<?php
/**
* 新增到个人用户
* @author xulei
* @since v1.0
* @modify 2014.9.25
* @copyright 深圳亿游
*/
require_once(LIB_PATH.'controller/root.con.php');
class MsgexCon extends rootCon {
    //将队列中的数据写入数据库
    public function crontabAction(){
        $index = myredis::getTailIndex("msg_list");
        $tailIndex = $index;
        $lastIndex = $this->getLastIndex();//上一次的数据取到位置

        $i = 0;
        while( true ){
            $i++;  if($i>10000) break;//一次最多处理多少条

            if($index <=$lastIndex) break;//
            $data = myredis::getValByIndex("msg_list",$index);

            var_dump($data);
            if(!$data || $data=='false') break;

            $msg = json_decode($data);
            $message = new Message();
            $message->status = STATUS_PUBLISH;
            $message->fromUid = $msg->loginUid;
            $message->toUid = $msg->toUid;
            $message->msg = $msg->msg;
            $message->created = $msg->time;
            $find = $message->find();
            if($find) continue;//重复消息不录入


            
            $user = new User();
            $user->find($message->fromUid);
            $message->fromNick = $user->nick;
            $message->fromAvatar = $user->avatar;

            
            $user = new User();
            $user->find($message->toUid);
            $message->toNick = $user->nick;
            $message->toAvatar = $user->avatar;
            $message->readStatus = $msg->readStatus;
            $message->isFromTeacher = $msg->isFromTeacher;
            $message->schoolId = $msg->schoolId;
            $message->teacherId = $msg->teacherId;

            

            if(($message->fromUid !=  $message->toUid) && $message->fromUid &&  $message->toUid){
                $saved = $message->save();
                /*if(!$saved){//存回去
                    echo "\r\nsave back \$message->fromUid=".$message->fromUid;
                    myredis::mypush("msgList",$data);
                }*/
            }

            $index--;
        }
        $this->saveLog($tailIndex);

        $this->j(0,'',['i'=>$i,'time'=>time()]);
    }

    public function sendAction(){
        $message = new Message();
        $message->readStatus = 0;
        $last = date('Y-m-d H:i:s',time()-3600*24);
        $sql = "SELECT * FROM ".$message->table()." WHERE readStatus=0 AND sendStatus=0 AND created>'$last'";
        $all = $message->query($sql);
        $list = [];
        foreach($all as $item){
            $list[$item['toUid']][] =  $item;
        }

        foreach($list as $uid=>$msgList){//给一个人最多发几条消息
            $content = "";
            if($msgList[0]['isFromTeacher']){ //发个学员只发最新的一条
                $time = myredis::get("lastSendTime".$msgList[0]['toUid']);
                echo (time()-$time)." isFromTeacher =1 \r\n";
                if((time()-$time) > 100){//超过半小时了
                    echo "send to {$msgList[0]['toUid']}\r\n";
                    myredis::set("lastSendTime".$msgList[0]['toUid'],time());


                    $school = new School();
                    $school->find($msgList[0]['schoolId']);

                    $teacher = new Teacher();
                    $teacher->find(['uid'=>$msgList[0]['fromUid']]);

                    myxiaochengxu::addTemplateKeyword($school->schoolName." ",1);
                    myxiaochengxu::addTemplateKeyword($teacher->teacherName." ",2);
                    myxiaochengxu::addTemplateKeyword($msgList[0]['msg'],3);

                    $fromUid = $msgList[0]['fromUid'];
                    $user = new User();
                    $user->find($uid);
                    $sendToOpenId = $user->openId;
                
                    
                    //pages/chat/chat?uid=目标ID&name=目标名称&avatar=目标头像
                    $user = new User();
                    $user->find($fromUid);
                    $fromNick = $user->nick;
                    $url = "pages/chat/chat?uid={$fromUid}";
                    $rect = myxiaochengxu::sendTemplateMsg($sendToOpenId,TEMPLATE_TONGZHI,$url);//教师给学员
                }else{
                    echo "not send to {$msgList[0]['toUid']}\r\n";
                }
            }else{//发给机构的
                echo " isFromTeacher =0 \r\n";
                $fromUid = $msgList[0]['fromUid'];
                $user = new User();
                $user->find($fromUid);
                $fromNick = $user->nick;
                myxiaochengxu::addTemplateKeyword($fromNick." ",1);

                $user = new User();
                $user->find($uid);
                myxiaochengxu::addTemplateKeyword(date('Y-m-d H:i',strtotime($msgList[0]['created'])),2);
                myxiaochengxu::addTemplateKeyword($msgList[0]['msg'],3);
                $rect = myxiaochengxu::sendTemplateMsg($user->openId,TEMPLATE_ZIXUN,"pages/chat/chat?uid={$fromUid}");//发给机构的
            }

            $tmpMessageObj = new Message();
            $tmpMessageObj->find($msgList[0]['messageId']);
            if($rect=='0'){//成功发送
                $tmpMessageObj->sendStatus = 1;
                $tmpMessageObj->sendResultCode = 0;
            }else{
                $tmpMessageObj->sendResultCode = $rect;
            }
            $tmpMessageObj->save();
        }


        print_r($list);
    }

    private function getLastIndex(){
        $messageLog = new MessageLog();
        $sql = "SELECT * FROM ".$messageLog->table()." ORDER BY ".$messageLog->key()." DESC LIMIT 1";
        $one = $messageLog->one($sql);
        return $one['tailIndex'];
    }

    private function saveLog($tailIndex){
        $messageLog = new MessageLog();
        $messageLog->tailIndex = $tailIndex;
        $messageLog->save();
    }


}

